import utils from '../../../utils/utils';
import Data from "../../../utils/data";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    previewBoxHeight: '',
    dict:{},
    share:{},
    title:'',
    des:'',
    previewImage:''
  },
  initPage: function (options) {
    if(options.hasOwnProperty('data')){
      let data = JSON.parse(decodeURIComponent(options['data']));
      let share = {}
      if (data.hasOwnProperty('image')){
        share['imageUrl'] = data.image
      }
      if (data.hasOwnProperty('title')) {
        share['title'] = data.title
      }
      if (data.hasOwnProperty('url')) {
        share['path'] = data.url
      }
      this.setData({
        share:share
      })
      console.log('分享参数：',share);
    }
    if (options.hasOwnProperty('title')) {
      this.setData({
        title: options.title
      })
    }
    if (options.hasOwnProperty('des')) {
      this.setData({
        des: options.des
      })
    }
    if (options.hasOwnProperty('img')) {
      this.setData({
        previewImage: options.img
      })
    }



    this.initPreviewHeight()
    this.initData();
  },
  initData(){
    let self =this
    Data.getDictConfig('task_config', function (res) {
      self.setData({
        dict: res
      })
    }, true);
  },
  initPreviewHeight() {
    let self = this
    let systemInfo = wx.getSystemInfoSync();
    let height = systemInfo.windowHeight;
    let rpxHeight = utils.rpxToPx(220);
    self.setData({
      previewBoxHeight: 'height:' + (height - rpxHeight) + 'px;',
    });
  },

  saveImage: function() {
    let self = this;
    let callback;
    if (self.data.previewImage === '') {
      utils.msg('请先获取分享图片');
      return false;
    }
    callback = function() {
      wx.getImageInfo({
        src: self.data.previewImage,
        success(res) {
          console.log(res);
          wx.saveImageToPhotosAlbum({
            filePath: res.path,
            success(res) {
              utils.msg('分享图片保存成功！');
            },
            fail(res) {
              utils.msg('分享图片保存失败，请稍候再试！');
              console.log('error', res)
            }
          });
        },
        fail(res) {
          utils.msg('分享图片拉取失败，请稍候再试！');
          console.log('error', res)
        }
      });
    };
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              callback();
            },
            fail() {
              utils.msg('您拒绝了保存权限，无法下载到相册');
            }
          })
        } else {
          callback();
        }
      },
      fail(res) {
        utils.msg('获取权限设置失败，请稍候再试！');
      }
    });
  },
  onShareAppMessage() {
    return this.data.share
  }
});
